package edu.sjb.characters;

import edu.sjb.Drawable;
import edu.sjb.constants.ImageConstants;
import edu.sjb.constants.ScoreConstants;
import edu.sjb.threads.SoundThread;

public class Koopa extends GameCharacter {
	protected boolean hitOnce;

	public Koopa() {
		super();
	}

	@Override
	public void hitAgainstMario(Mario m) {

		if (!m.underStarEffect()) {
			if ((m.posY() <= posY() - 16) && !m.underSuperMushroomEffect()) {
				SoundThread.koopaCrush();
				if (hitOnce) {
					game().changeScore(ScoreConstants.KOOPA_CRUSHED);
					die();
				}
				else {
					hitOnce = true;
					shiftPosX(250);
					setPosY(512);
					image.changeImage(ImageConstants.KOOPA_CRUSHED);
				}
			}
			else {
				if (m.underSuperMushroomEffect()) {
					if ((m.posY() + 32 >= posY())) {
						game().mario().setUnderSuperMushroomEffect(false);
						m.shrink();
						if (m.posX() < posX()) {
							m.shiftPosX(m.posX() + 32);
						}
						else {
							m.setPosX(m.posX() - 64);
						}
					}
					else {
						SoundThread.koopaCrush();
						if (hitOnce) {
							game().changeScore(ScoreConstants.KOOPA_CRUSHED);
							die();
						}
						else {
							hitOnce = true;
							shiftPosX(250);
							setPosY(512);
							image.changeImage(ImageConstants.KOOPA_CRUSHED);
						}
					}
				}
				else {
					if (!m.gravity().onAir()) {
						game().changeScore(ScoreConstants.KOOPA_HIT);
						m.die();
					}
				}

			}
		}
		else {
			SoundThread.koopaCrush();
			game().changeScore(ScoreConstants.KOOPA_CRUSHED);
			die();
		}
	}

	@Override
	public void characterCollide(GameCharacter gc) {
	}

	@Override
	public void die() {

		try {
			Thread.sleep(20);
		}
		catch (InterruptedException e) {
		}
		game().removeEntity(this);

	}

	@Override
	public void run() {
		while (!hitOnce) {
			image.changeImage(ImageConstants.KOOPA_WALK_R);
			for (int i = 0; i < 150 && !hitOnce && canGoRight(); i++) {
				if (!canGoLeft()) {
					setCanGoLeft(true);
				}
				shiftPosX(15);
				try {
					Thread.sleep(40);
				}
				catch (InterruptedException e) {
				}
			}
			image.changeImage(ImageConstants.KOOPA_WALK_L);
			for (int i = 0; i < 150 && !hitOnce && canGoLeft(); i++) {
				if (!canGoRight()) {
					setCanGoRight(true);
				}
				shiftPosX(-15);
				try {
					Thread.sleep(40);
				}
				catch (InterruptedException e) {
				}
			}
		}
	}

	protected Object clone() {
		Koopa koopa = new Koopa();
		Drawable img = new Drawable(ImageConstants.KOOPA_WALK_R, false);
		koopa.setImage(img);
		return koopa;
	}
}
